#include<iostream>
#include<unistd.h>
#include<cassert>
#include<cstring>
#include<cstdio>
#include<cstdlib>
#include<sys/wait.h>
#include<sys/types.h>
#include<fcntl.h>
using namespace std;

#define NUM 1024

int main()
{
    int pipefd[2]={0};
    int ret=pipe(pipefd);//[0]读端，[1]写端
    assert(ret!=-1);//debug下有效

#ifdef DEBUG//条件编译
    cout<<"pipefd[0]:"<<pipefd[0]<<endl;
    cout<<"pipefd[1]:"<<pipefd[1]<<endl;
#endif

    pid_t id=fork();//创建子进程
    assert(id!=-1);
    if(id==0)//子进程读取
    {
        close(pipefd[1]);//关闭写端
        char buffer[NUM]={0};
        int count=0;
        while(true)
        {
            // count++;
            ssize_t s=read(pipefd[0],buffer,sizeof(buffer));//从管道读
            if(s>0)
            {
                buffer[s]=0;
                printf("child read[%d]:%s\n",getpid(),buffer);
            }else if(s==0)
            {
                cout<<"father quit,child quit"<<endl;
                break;
            }

        }
        close(pipefd[0]);
        exit(0);
    }
    else//父进程写入
    {
        close(pipefd[0]);//关闭读端
        string message="I am father process";
        int count=0;
        char send_buffer[NUM];
        while(true)
        {
            snprintf(send_buffer,sizeof(send_buffer),"%s[%d]",message.c_str(),count++);
            //往buffer里格式化写入
            write(pipefd[1],send_buffer,strlen(send_buffer));
            //写入管道
            sleep(1);//控制频率
        }
        close(pipefd[1]);
        pid_t ret=waitpid(id,NULL,0);
        assert(ret!=-1);

    }
    return 0;
}